const UniPayService = require('./unipay.js')
const uniPay = require('uni-pay');
/**
 * 微信支付处理
 */
module.exports = class WxpayService extends UniPayService {
	constructor(ctx) {
		super(ctx)
		this.type = "wxpay";
		this.payname = "微信";
	}
	async prepay(userInfo) {
		return {
			key: this.type,
			icon: "icon_pay_wxpay",
			color: "#00aa00",
			name: this.payname,
			confirm: false
		}
	}
	/**
	 *  验证
	 *  https://uniapp.dcloud.io/uniCloud/unipay?id=%e6%94%af%e4%bb%98%e7%bb%93%e6%9e%9c%e9%80%9a%e7%9f%a5%e5%a4%84%e7%90%86
	 */
	async verify(config, event, next) {
		let uniPayIns = uniPay[config["uniPay"]](config);
		//如果验证失败，会抛出异常，成功才能进入下面
		let res = await uniPayIns.verifyPaymentNotify(event);
		console.log("uniPayIns.verifyPaymentNotify", res)
		res.type = this.type;
		//处理各类订单支付完成之后的回调res.pfx = fs.readFileSync(fullPath);
		await next(res);
		//返回成功字符串
		return this.returnNotifyData();
	}


	/**
	 * 微信企业转账到微信零钱，开通此功能需要特殊的要求
	 * @param {Object} data {amount,_id,user}
	 * @param {string} platform 平台
	 * https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
	 */
	async transfers(data, platform, desc) {
		console.log("transfers", platform, desc)
		//前端登录配置，获得的openid才能对应
		let transferConfig = this.ctx.getConfigs.paymentConfigs("weixin", "transfers");
		if (data.user && data.user.appid) {
			//必须保证appid与openid匹配
			transferConfig.appId = data.user.appid;
		}
		console.log("config", transferConfig)
		let uniPayIns = uniPay["initWeixin"](transferConfig);
		let openid = this.getOpenid(data.user, platform)
		console.log("transfers", data)
		uniPayIns.paths["mmpaymkttransfers"] = "/mmpaymkttransfers/promotion/transfers"
		//https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers
		let publicParams = uniPayIns._getPublicParams();
		console.log("publicParams", publicParams)
		const requestOptions = {
			amount: data.amount,
			desc,
			openid,
			partner_trade_no: data._id,
			check_name: "NO_CHECK",
			mch_appid: publicParams.appid, //商户账号appid字段名不同
			mchid: publicParams.mchId, //微信支付分配的商户号
			nonce_str: publicParams.nonceStr
		}
		console.log("requestOptions", requestOptions)
		try {
			//简易版XML转Object，只可在微信支付时使用，不支持嵌套
			uniPayIns.parseXML = function(xml) {
				const xmlReg = /<(?:xml|root).*?>([\s|\S]*)<\/(?:xml|root)>/
				const str = xmlReg.exec(xml)[1]
				const obj = {}
				const nodeReg = /<(.*?)>(?:<!\[CDATA\[){0,1}(.*?)(?:\]\]>){0,1}<\/.*?>/g
				let matches = null
				// eslint-disable-next-line no-cond-assign
				while ((matches = nodeReg.exec(str))) {
					obj[matches[1]] = matches[2]
				}
				return obj
			}
			//格式化
			uniPayIns._parse = function(xml, apiName, signType) {
				const json = this.parseXML(xml)
				console.log("json", json)
				if (json.return_code === 'FAIL') throw new Error(`${json.return_msg}`)
				if (apiName !== 'getSandboxKey') {
					if (json.mch_appid !== this.options.appId) throw new Error('appId不匹配')
					if (json.mchid !== this.options.mchId) throw new Error('mchId不匹配')
					// 特殊处理appId
					json.app_id = json.mch_appid
					delete json.mch_appid
				}

				if (json.result_code === 'FAIL') {
					throw new Error(`${json.err_code} ${json.err_code_des}`)
				}
				return this._normalizeResult(json, apiName)
			}
			//必须验证证书
			const result = await uniPayIns._requestWxpay(requestOptions, 'mmpaymkttransfers', true);
			console.log(result)
			return result;
		} catch (e) {
			console.log(e)
			return {
				code: -1,
				message: e.message
			}
		}
		return false;
	}
	/**
	 * 返回给微信服务器
	 */
	returnNotifyData() {
		return {
			header: "text/xml;charset=utf-8",
			result: "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"
		}
	}

	getOpenid(userInfo, platform) {
		if (!platform) {
			platform = this.ctx.context.PLATFORM;
		}
		if (userInfo.wx_openid) {
			return userInfo.wx_openid[platform];
		}
		return false;
	}
}
